<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\CacheCart;
use app\api\model\Cart as Carts;

class Cart extends Api
{
	protected $noNeedLogin = [];
	protected $noNeedRight = ['*'];
    protected $gmodel;
	public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->model = new CacheCart($this->user_id);
        $this->gmodel = new Carts();
    }

    /**
     * [add 加入購物車]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T18:39:23+0800
     */
    public function add()
    {
        $goods_id = $this->request->post("goods_id", 0);
        $goods_num = $this->request->post("goods_num", 1);
        $goods_sku_id = $this->request->post("goods_sku_id", '');
        if ( !$goods_id ) {
            $this->error('請選擇商品');
        }

        if (!$this->gmodel->addCart($this->user_id,$goods_id, $goods_num, $goods_sku_id)) {
            $this->error($this->gmodel->getError() ?: '加入购物车失败');
        }
        $total_num = $this->gmodel->getTotalNum($this->user_id);
        $this->success('操作成功',['cart_total_num' => $total_num]);
    }

    /**
     * [sub 刪減購物車]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T18:49:23+0800
     * @return     [type]                   [description]
     */
    public function sub(){

        $goods_id = $this->request->post("goods_id", 0);
        $goods_sku_id = $this->request->post("goods_sku_id", '');
        $goods_num = $this->request->post("goods_num", 1);
        if ( !$goods_id ) {
            $this->error('請選擇商品');
        }

        if(!$this->gmodel->subCart($this->user_id,$goods_id, $goods_sku_id,$goods_num)){
            $this->error($this->gmodel->getError() ?: '刪減购物车失败');
        }
        $total_num = $this->gmodel->getTotalNum($this->user_id);
        $this->success('操作成功',['cart_total_num' => $total_num]);
    }

    /**
     * [getTotalNum 获得购物车商品数量]
     * @MethodName
     * @Author     Allen
     * @DateTime   2021-10-15T18:52:52+0800
     * @return     [type]                   [description]
     */
    public function getTotalNum(){
        $total_num = $this->gmodel->getTotalNum($this->user_id);
        $this->success('請求成功',['cart_total_num' => $total_num]);
    }

    // 購物車列表
    public function getlists()
    {
        $this->success('請求成功',$this->gmodel->getList($this->user_id));
    }


    public function delete()
    {
        $rq_data = $this->request->request();
        $goods_id = $rq_data['goods_id'];
        $goods_sku_id = $rq_data['goods_sku_id'];
        $this->model->delete($goods_id, $goods_sku_id);
        $this->success('操作成功');
    }

}

